//
//  PortfilioDetailViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/3.
//  Copyright © 2020 王洋. All rights reserved.
//
#import <SDImageCache.h>
#import "LSTPopView.h"
#import "CLPlayerView.h"

#import "PoftfilioNameCell.h"
#import "SamplePhotoCell.h"
#import "PoftfilioStoreInfoCell.h"
#import "PoftfilioPackageCell.h"
#import "PoftfilioWebCell.h"
#import "CommonFullScreenVideoCell.h"

#import "PoftfilioDetailBottomView.h"

#import "StoreDetailViewController.h"
#import "TT_ConversationDetailViewController.h"
#import "MessageCenterViewController.h"
#import "StoreHotelDetailViewController.h"
#import "PortfilioDetailViewController.h"


@interface PortfilioDetailViewController ()<UITableViewDelegate, UITableViewDataSource, CLCommonTableViewCellDelegate,PoftfilioWebCellDelegate>

@property (nonatomic, strong) CommonOpusModel *model;

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) PoftfilioDetailBottomView *bottomView;

/**CLplayer*/
@property (nonatomic, weak) CLPlayerView *playerView;
/**记录Cell*/
@property (nonatomic, assign) UITableViewCell *cell;

@property (nonatomic, assign) NSTimeInterval lastTime;

@end

@implementation PortfilioDetailViewController

- (void)dealloc {
    
    [self.playerView pausePlay];
    [self.playerView destroyPlayer];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];

    
    [self.playerView pausePlay];
    [self.playerView destroyPlayer];

    [self handleStep];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleStep) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleStep) name:UIApplicationWillTerminateNotification object:nil];
    
    self.lastTime = [Utilities getCurrentServerTimestamp];
}

- (void)appBecomeActive {
    self.lastTime = [Utilities getCurrentServerTimestamp];
}

- (void)handleStep {

    [[BA_BusinessHelper shared] addFootPrintWith:self.soId lastTime:self.lastTime And:self.model.sellerId type:BusinessCollectType_case];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self request_caseDetail];

    [self initView];
}

- (void)initView {

    self.title = @"案例详情";
    self.view.backgroundColor = UIColorHex(0xf1f1f1);
    
    [self.view addSubview:self.tableview];
    [self.view addSubview:self.bottomView];

    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(60);
        make.bottom.mas_equalTo(-Bottom_SafeHeight);
    }];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        //make.bottom.mas_equalTo(self.bottomView.mas_top).offset(-1);
        make.bottom.mas_equalTo(0);
    }];
        
    UIButton *imBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    imBtn.frame = CGRectMake(0,0,40,30);
    [imBtn setImage:[UIImage imageNamed:@"store_xiaoxi_b"] forState:UIControlStateNormal];
    [imBtn addTarget:self action:@selector(goIm) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *imItem = [[UIBarButtonItem alloc] initWithCustomView:imBtn];
    
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shareBtn.frame = CGRectMake(0,0,40,30);
    [shareBtn setImage:[UIImage imageNamed:@"store_fenxiang_b"] forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(goShare) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *shareItem = [[UIBarButtonItem alloc] initWithCustomView:shareBtn];

    self.navigationItem.rightBarButtonItems =@[imItem,shareItem];
    
    [self initViewAction];
    
    [RACObserve([TT_MessageManager manager], totalUnReadCount) subscribeNext:^(id x) {
        if ([TT_MessageManager manager].totalUnReadCount > 0) {
            imBtn.badgeValue = [NSString stringWithFormat:@"%d",[TT_MessageManager manager].totalUnReadCount];
            imBtn.badgeBGColor = [UIColor redColor];
        } else {
            imBtn.badgeValue = @"";
            imBtn.badgeBGColor = [UIColor clearColor];
        }
    }];
    self.bottomView.hidden = YES;
}

- (void)goIm {
    MessageCenterViewController *vc = [[MessageCenterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)goShare {
    
    [self share];
}

- (void)initViewAction {
    
    WEAKSELF
    self.bottomView.PoftfilioDetailBottomViewBlock = ^(PoftfilioDetailBottomType type) {
      
        switch (type) {
            case PoftfilioDetailBottomType_store:{
                
                if ([weakSelf.model.classId isEqualToString:Store_Category_Hotel]) {
                    StoreHotelDetailViewController *vc = [[StoreHotelDetailViewController alloc] init];
                    vc.storeId = weakSelf.model.sellerId;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                    
                } else {
                    StoreDetailViewController *vc = [[StoreDetailViewController alloc] init];
                    vc.storeId = weakSelf.model.sellerId;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
            } break;
            case PoftfilioDetailBottomType_collect:{
                [[BA_BusinessHelper shared] callCollectStoreWith:weakSelf.soId
                                                   currentStatus:weakSelf.model.isCollect
                                                            type:BusinessCollectType_case
                                                        comption:^(BOOL success) {
                    weakSelf.model.isCollect = !weakSelf.model.isCollect;
                    [weakSelf refreshBottomStatus];
                }];
            } break;
            case PoftfilioDetailBottomType_phone:{
                [[TT_PhonaCallManager manager] callWithStoreId:weakSelf.model.sellerId];
            } break;
            case PoftfilioDetailBottomType_subscribe:{
                [[BA_BusinessHelper shared] callSubscribeStoreWith:weakSelf.model.sellerId];
            } break;
            case PoftfilioDetailBottomType_im:{
                [[TT_IMContactManager manager] ImContactWithStoreId:weakSelf.model.sellerId];
            } break;
            default:
                break;
        }
    };
}

#pragma mark Share
- (void)share {
    
    CommonShareModel *model = [[CommonShareModel alloc] init];
    model.url = [NSString stringWithFormat:@"%@%@?soId=%@&myCode=%@",BA_GlobalH5_Domain,@"/worksDetail",self.model.soId,[TTUserModel sharedObject].myCode];
    model.title = self.model.opusName;
    model.content = @"婚前婚后邀您体验";
    
    if (self.model.transverseImg.length > 0) {
        model.image = self.model.transverseImg;
    }
    [[TT_ShareManager share] callShareViewWithModel:model];
    
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
        case PortfilioDetailCellType_samplePhoto:{
            return TTScreenWidth * 0.6;
        } break;
        case PortfilioDetailCellType_name:{
            return [Utilities getStringHeightWithText:self.model.opusName font:[UIFont systemFontOfSize:16 weight:UIFontWeightBold] viewWidth:(TTScreenWidth - 32)] + 20;
        } break;
        case PortfilioDetailCellType_storeInfo:{
            return 85;
        } break;
        case PortfilioDetailCellType_packageInfo:{
            return 120;
        } break;
        case PortfilioDetailCellType_web:{
            return _model.richTextModel.richTextModulesHeight;
        } break;
            
        default:
            break;
    }
    return 100;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WEAKSELF
    switch (indexPath.row) {
        case PortfilioDetailCellType_samplePhoto:{
            
            CommonFullScreenVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommonFullScreenVideoCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            
            NSString *verticalImg = [TT_OSSManager reSourceUrl:self.model.transverseImg type:BA_resizeType_max];
            [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:verticalImg] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            
            if (self.model.opusVideo.length > 0) {
                cell.playBtn.hidden = NO;
            } else {
                cell.playBtn.hidden = YES;
            }
            
            cell.delegate = self;
            
            return cell;
            
        } break;
        case PortfilioDetailCellType_name:{

            PoftfilioNameCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PoftfilioNameCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            cell.mainTitleLab.text = self.model.opusName;
            return cell;
        } break;
        case PortfilioDetailCellType_storeInfo:{
            
            PoftfilioStoreInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PoftfilioStoreInfoCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            [cell fillCellWithModel:self.model];
            
            cell.PoftfilioStoreInfoBlock = ^{
              
                if ([weakSelf.model.classId isEqualToString:Store_Category_Hotel]) {
                    StoreHotelDetailViewController *vc = [[StoreHotelDetailViewController alloc] init];
                    vc.storeId = weakSelf.model.sellerId;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                    
                } else {
                    StoreDetailViewController *vc = [[StoreDetailViewController alloc] init];
                    vc.storeId = weakSelf.model.sellerId;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
            };
            return cell;
            
        } break;
        case PortfilioDetailCellType_packageInfo:{
            
            PoftfilioPackageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PoftfilioPackageCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
        //    [cell fillCellWithModel:self.dataArray[indexPath.section].goodsList[indexPath.row]];
            return cell;
            
        } break;
        case PortfilioDetailCellType_web:{
            
            PoftfilioWebCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PoftfilioWebCellID"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
            if (_model) {
                cell.richTextModel = self.model.richTextModel;
            }
            cell.parentVC = self;
            return cell;
            
        } break;
            
        default:
            break;
    }
    SamplePhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SamplePhotoCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
//    [cell fillCellWithModel:self.dataArray[indexPath.section].goodsList[indexPath.row]];
    return cell;
}

//在willDisplayCell里面处理数据能优化tableview的滑动流畅性，cell将要出现的时候调用
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
//    CommonFullScreenVideoCell * myCell = (CommonFullScreenVideoCell *)cell;
//    myCell.model = self.dataArray[indexPath.row];
//    [myCell.coverImageView sd_setImageWithURL:[NSURL URLWithString:self.model.transverseImg]];

//    [myCell fillCellWithModel:self.dataArray[indexPath.row]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

//cell离开tableView时调用
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //因为复用，同一个cell可能会走多次
    if ([_cell isEqual:cell]) {
        //区分是否是播放器所在cell,销毁时将指针置空
        [_playerView destroyPlayer];
        _cell = nil;
    }
}
#pragma mark - PoftfilioWebCell
- (void)poftfilioWebCellBackHeight:(CGFloat)cellHeight
{
    _model.richTextModel.richTextModulesHeight = cellHeight;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableview reloadData];
    });
}
#pragma mark - 点击播放代理
- (void)cl_commonTableViewCellPlayVideoWithCell:(CommonFullScreenVideoCell *)cell {
    //记录被点击的Cell
    _cell = cell;
    //销毁播放器
    [_playerView destroyPlayer];
    CLPlayerView *playerView = [[CLPlayerView alloc] initWithFrame:CGRectMake(0, 0, TTScreenWidth, TTScreenWidth*0.6)];
    _playerView = playerView;
    [cell.contentView addSubview:_playerView];
    //视频地址
    _playerView.url = [NSURL URLWithString:self.model.opusVideo];

    [_playerView updateWithConfigure:^(CLPlayerViewConfigure *configure) {
        configure.topToolBarHiddenType = TopToolBarHiddenSmall;
//        config.smallGestureControl = YES;
    }];
    //播放
    [_playerView playVideo];
    //返回按钮点击事件回调
    [_playerView backButton:^(UIButton *button) {
        NSLog(@"返回按钮被点击");
    }];
    //播放完成回调
    [_playerView endPlay:^{
        //销毁播放器
        [self->_playerView destroyPlayer];
        self->_playerView = nil;
        self->_cell = nil;
        NSLog(@"播放完成");
    }];
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"CommonFullScreenVideoCell" bundle:nil] forCellReuseIdentifier:@"CommonFullScreenVideoCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"SamplePhotoCell" bundle:nil] forCellReuseIdentifier:@"SamplePhotoCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"PoftfilioStoreInfoCell" bundle:nil] forCellReuseIdentifier:@"PoftfilioStoreInfoCellID"];

        [_tableview registerNib:[UINib nibWithNibName:@"PoftfilioNameCell" bundle:nil] forCellReuseIdentifier:@"PoftfilioNameCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"PoftfilioPackageCell" bundle:nil] forCellReuseIdentifier:@"PoftfilioPackageCellID"];

        [_tableview registerClass:[PoftfilioWebCell class] forCellReuseIdentifier:@"PoftfilioWebCellID"];
        
        
    }
    return _tableview;
}

//- (SubscribeModel *)subscribeModel {
//    if (!_subscribeModel) {
//        _subscribeModel = [[SubscribeModel alloc] init];
//    }
//    return _subscribeModel;
//}

- (PoftfilioDetailBottomView *)bottomView {
    
    if (!_bottomView) {
        _bottomView =  [[NSBundle mainBundle] loadNibNamed:@"PoftfilioDetailBottomView"owner:nil options:nil].firstObject;
    }
    return _bottomView;
}

- (void)request_caseDetail {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    
    [dic setValue:self.soId forKey:@"soId"];
    
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    
    [SVProgressHUD showWithStatus:@"正在加载案例详情"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CaseDetail];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];

                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                 
                    NSArray *industryTheme = [resultDic valueForKey:@"industryTheme"];
                    NSArray *images = [resultDic valueForKey:@"images"];
                    NSDictionary *userCollection = [resultDic valueForKey:@"userCollection"];
                    
                    weakSelf.model = [CommonOpusModel modelWithDictionary:resultDic];

                    if (weakSelf.model.isUp == 2) {
                        [TT_Alert alert:@"该案例已下架" doneAction:^{
                            [weakSelf.navigationController popViewControllerAnimated:YES];
                        }];
                        return;
                    }
                    
                    weakSelf.model.userCollection = [CommonFavorModel modelWithDictionary:userCollection];
                    
                    if (weakSelf.model.userCollection.isDel == 2) {
                        weakSelf.model.isCollect = YES;
                    } else {
                        weakSelf.model.isCollect = NO;
                    }
                    
                    
                    if ([industryTheme isKindOfClass:[NSArray class]]) {
                        weakSelf.model.industryTheme = @[].mutableCopy;
                        for (int i = 0; i < industryTheme.count; i++) {
                            NSDictionary *themeDic = industryTheme[i];
                            CommonThemeModel *themeModel = [CommonThemeModel modelWithDictionary:themeDic];
                            [weakSelf.model.industryTheme addObject:themeModel];
                        }
                    }
                    [weakSelf prepareData];
                    [weakSelf refreshBottomStatus];
                    [weakSelf.tableview reloadData];
                    
                    
                    if ([TTUserModel sharedObject].userId.length > 0) {
                        [[BA_BusinessHelper shared] browseStore:weakSelf.model.sellerId type:BusinessActionType_tcs comption:^(BOOL success) {}];
                    }

                }
                
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
    
}
- (void)prepareData {
    CommonOpusModel *detailModel = self.model;
    //组合数据
    CommentRichTextModel *richTextModel = [[CommentRichTextModel alloc]init];
    richTextModel.richContent = detailModel.opusDetail;
    richTextModel.images = detailModel.images;
    detailModel.richTextModel = richTextModel;
    //组合数据
    //richContentAttriteStr、richTextFrame
    NSMutableAttributedString *titleAttributes = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@",richTextModel.richContent]];
    titleAttributes.font = kFontRegular14;
    titleAttributes.color = kColor51;
    titleAttributes.lineSpacing = 5*ADAPTER_WIDTH;
    richTextModel.richContentAttriteStr = titleAttributes;
    richTextModel.richTextFrame = CGRectMake(10*ADAPTER_WIDTH, 10*ADAPTER_WIDTH, WIDTH - 20*ADAPTER_WIDTH, [YYTextLayout layoutWithContainerSize:CGSizeMake(WIDTH - 20*ADAPTER_WIDTH, MAXFLOAT) text:titleAttributes].textBoundingSize.height);
    
    //richImageModulesTop
    richTextModel.richImageModulesTop = richTextModel.richContent.length == 0 ? 10*ADAPTER_WIDTH : CGRectGetMaxY(richTextModel.richTextFrame) + 20*ADAPTER_WIDTH;
    //预先加载
    CGFloat cacheNumber = 0;
    CGFloat shouldLoadingNumber = 0;
    SDImageCache *cache = [SDImageCache sharedImageCache];
    CGFloat orinY = richTextModel.richImageModulesTop;
    for (NSInteger index = 0; index < richTextModel.images.count; index ++) {
        CommonMediaModel *mediaModel = richTextModel.images[index];
        UIImage *orinImage = [cache imageFromDiskCacheForKey:mediaModel.url];
        if ([cache diskImageDataExistsWithKey:mediaModel.url] && orinImage) {
            cacheNumber = cacheNumber + 1;
            mediaModel.itemHeight = WIDTH * orinImage.size.height / orinImage.size.width;
            orinY = orinY + mediaModel.itemHeight;
        } else {
            shouldLoadingNumber = shouldLoadingNumber + 1;
            mediaModel.itemHeight = 300*ADAPTER_WIDTH;
        }
    }
    if (richTextModel.images.count == 0) {
        richTextModel.richTextModulesHeight = orinY;
        richTextModel.allImagesCache = NO;
    } else {
        if (cacheNumber == richTextModel.images.count) {
            richTextModel.richTextModulesHeight = orinY;
            richTextModel.allImagesCache = YES;
        } else {
            CGFloat orinY = richTextModel.richImageModulesTop;
            orinY = orinY + richTextModel.images.count * richTextModel.images.firstObject.itemHeight;
            richTextModel.richTextModulesHeight = orinY;
            richTextModel.allImagesCache = NO;
            //预先加载把
            for (NSInteger index = 0; index < richTextModel.images.count; index ++) {
                NSString *url = richTextModel.images[index].url;
                [[[UIImageView alloc]init]sd_setImageWithURL:url.wppURL completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                    
                }];
            }
        }
    }
}
- (void)refreshBottomStatus {
    if (self.model.isCollect) {
        [self.bottomView.favorImageView setImage:[UIImage imageNamed:@"store_shoucang_sel"]];
    } else {
        [self.bottomView.favorImageView setImage:[UIImage imageNamed:@"store_shoucang"]];
    }
}


@end
